package com.turtle3d.util;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Hashtable;

import com.turtle3d.App;

/**
 * Singleton class for time measurement.
 * @author Marek Paterczyk <marek.paterczyk@gmail.com>
 *
 */
public class TaskTimer {
		
	private Hashtable<String, TimedTask> processes = new Hashtable<String, TimedTask>();
	
	private DecimalFormat secondsFormat = new DecimalFormat("0.00");
	
	private static TaskTimer taskTimer;
	
	public static TaskTimer getTaskTimer(){
		if(taskTimer==null)
			taskTimer = new TaskTimer();
		
		return taskTimer;
	}
	
	public void taskStart(String taskName){
		processes.put(taskName, new TimedTask());
	}
	
	public void taskStart(String taskName, String taskDecription){
		processes.put(taskName, new TimedTask(taskDecription));
	}
	
	public long taskComplete(String taskName){
		TimedTask task = processes.get(taskName);
		task.stop();				
		
		String desc = task.getDescription()==null?taskName:task.getDescription();		
		App.println(this.getClass().getSimpleName()+" "+desc+": "+formatedTaskTime(taskName));
		
		return processes.get(taskName).getTime();
	}
	
	public long taskTime(String taskName){
		return processes.get(taskName).getTime();
	}
	
	public String formatedTaskTime(String taskName){
		return formatTime(taskTime(taskName));
	}
	
	public String formatTime(long seconds){
		return secondsFormat.format(seconds/1000.)+"s";
	}

	public DecimalFormat getSecondsFormat() {
		return secondsFormat;
	}

	public void setSecondsFormat(DecimalFormat secondsFormat) {
		this.secondsFormat = secondsFormat;
	}
	
	private class TimedTask {
		
		private Date start = null;
		private Date finish = null;
		
		private String description;
		
		public TimedTask(String description) {			
			start = new Date();
			this.description = description;
		}

		public TimedTask(){
			start = new Date();
		}
		
		public void stop(){
			finish = new Date();
		}
		
		public long getTime(){
			if(finish==null)		
				return ((new Date()).getTime()-start.getTime());
			else
				return finish.getTime()-start.getTime();
		}

		public String getDescription() {
			return description;
		}

		public void setDescription(String description) {
			this.description = description;
		}
		
		
		
	}
	
}
